package com.haozi.ehub.core.util;

import com.haozi.ehub.core.model.Email;

import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Date;
import java.util.Properties;

/**
 * 发送邮件工具类
 * @author     ： terry
 * @date       ： Created in 2020/6/11 17:01
 */
public class EmailUtils {
    /**
     * 发送邮件
     * @author     ： terry
     * @date       ： Created in 2020/6/11 17:00
     * @param: emailVo 邮件实体类
     */
    public static void sendEmail(Email emailVo){
        // 参数配置
        Properties props = new Properties();
        props.setProperty("mail.transport.protocol", "smtp");
        props.setProperty("mail.smtp.host", CodeUtils.SMTP_HOST);
        props.setProperty("mail.smtp.auth", "true");
        props.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
        props.setProperty("mail.smtp.port", "465");
        props.setProperty("mail.smtp.socketFactory.port", "465");
        // 根据配置创建会话对象,用于和邮件服务器交互
        Session session = Session.getDefaultInstance(props);
        // 设置为debug模式,可以查看详细的发送log
        session.setDebug(true);
        // 创建一封邮件
        Message message = createEmail(session, emailVo);
        // 根据Session获取邮件传输对象
        try {
            Transport transport = session.getTransport();
            // 使用邮箱账号和授权码连接邮件服务器, 这里认证的邮箱必须与message中的发件人邮箱一致,否则会报错
            transport.connect(CodeUtils.SEND_EMAIL_ACCOUNT, CodeUtils.MAIL_AUTHORIZATION_CODE);
            // 发送邮件
            transport.sendMessage(message, message.getAllRecipients());
            // 关闭连接
            transport.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    /**
     * 生成邮件
     * @author     ： terry
     * @date       ： Created in 2020/6/11 16:58
     * @param: session
     * @param: emailVo
     * @return： Message
     */
    private static Message createEmail(Session session, Email email){
        Message message = new MimeMessage(session);
        try{
            //生成发送邮件地址
            InternetAddress sendInternetAddress = new InternetAddress(CodeUtils.SEND_EMAIL_ACCOUNT);
            //生成接收邮件地址
            InternetAddress receiveInternetAddress = new InternetAddress(email.getReceiveMailAccount());
            //设置发送邮件方
            message.setFrom(sendInternetAddress);
            //设置接收邮件方
            message.setRecipient(MimeMessage.RecipientType.TO, receiveInternetAddress);
            // 设置邮件标题
            message.setSubject(email.getMailTitle());
            // 设置邮件正文
            message.setText(email.getMailContent());
            //设置邮件发出日期
            message.setSentDate(new Date());
            //保存设置
            message.saveChanges();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return message;
    }
}
